import {uSelectDevStatus, uSelectDevLogByPage} from '@/api/setting'
import {observable, action, computed} from 'mobx'
import {createContext} from 'react'
import Taro from '@tarojs/taro'
import ChildrenPageUtils from '@/store/extends'

export enum LogType {
  running = '0058',
  abnormal = '0060',
  operate = '0059'
}

class Devlog extends ChildrenPageUtils {
  @observable currentSwitch: LogType = LogType.running

  @action.bound
  changeCurrentSwitch(current: LogType) {
    this.currentSwitch = current
    this.logList = []
    this.resetPagination()
    this.updateLogList()
  }

  @observable startDate: string = ''
  @observable endDate: string = ''
  @computed get dateRange(): [string, string] | null {
    if (!this.startDate) return null
    if (!this.endDate) return null
    return [this.startDate + ' 00:00:00', this.endDate + ' 23:59:59']
  }

  @action.bound
  changeDateRange(s: string, e: string) {
    this.startDate = s
    this.endDate = e
    this.logList = []
    this.resetPagination()
    this.updateLogList()
  }

  @observable logList: Setting.LogData[] = []
  @action.bound
  async updateLogList() {
    Taro.showLoading({
      title: '加载中...',
      mask: true
    })
    setTimeout(() => {
      Taro.hideLoading()
    }, 1500)
    let devId = this.pageQuery.devId
    if (!devId) return
    let dateRange = this.dateRange
    if (!dateRange) return
    this.closeUpdate()
    Taro.showLoading()

    let res = await uSelectDevLogByPage({
      devId: devId,
      page: this.pagination.page,
      startDate: dateRange[0],
      endDate: dateRange[1],
      devLogTypeCode: this.currentSwitch
    })

    if (res && res.result === 'success') {
      if (!res.data.list.length && this.pagination.page === 1) {
        Taro.showToast({
          icon: 'none',
          title: '暂无日志记录'
        })
      }
      this.logList.push(...res.data.list)
      this.updatePagination({
        page: res.data.page,
        total: res.data.total,
        totalPage: res.data.totalPage
      })
    } else {
      this.delPage()
    }
    this.openUpdate()
    Taro.hideLoading()
  }

  @observable devStatus: Setting.DevStatus | null = null
  @action.bound
  async updateDevStatus() {
    if (!this.pageQuery.devId) return
    let res = await uSelectDevStatus({devId: this.pageQuery.devId})
    if (res && res.result === 'success') {
      this.devStatus = res.data
    } else {
      this.devStatus = null
    }
  }

  @action.bound
  clearPageData() {
    this.devStatus = null
    this.logList = []
    this.currentSwitch = LogType.running
  }
}

export const devLogStore = createContext(new Devlog())
